<template>
  <div>
    <a-row :gutter="[20, 0]">
      <a-col :span="6">
        <a-card
          :body-style="{ padding: '24px 32px' }"
          :bordered="false"
          class="menu"
        >
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: space-between;
            "
          >
            <a-tree
              :tree-data="treeData"
              :replaceFields="replaceFields"
              :defaultExpandAll="true"
              @select="selectTreeNode"
            >
            </a-tree>
          </div>
        </a-card>
      </a-col>
      <a-col style="background: #fff" :span="18">
        <div class="conditionsSearch">条件搜索</div>

        <div class="search-wrapper">
          <!-- 头部搜索 -->

          <a-form-model
            class="topAntform"
            ref="searchFormRef"
            :model="searchFormData"
          >
            <a-form-model-item label="姓名:" class="serach-input">
              <a-input
                placeholder="请输入"
                size="large"
                v-model="searchFormData.name"
              />
            </a-form-model-item>
          </a-form-model>
          <!-- 按钮组 -->
          <div class="btn-group">
            <a-button
              type="success"
              icon="search"
              @click="searchBtnClick"
              style="background-color: #0079fe; color: #fff"
            >
              查询
            </a-button>
            <!-- <a-button @click="resetBtnClick">重置</a-button> -->
          </div>
        </div>
        <a-card :body-style="{ padding: '10px 0px' }" :bordered="false">
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
              height: 30px;
              float: right;
              margin-bottom: 10px;
              justify-content: space-between;
            "
          >
            <span
              style="
                padding-left: 12px;
                color: rgba(0, 0, 0, 0.85);
                font-size: 14px;
              "
              >当前有<span style="padding: 0 3px">{{ tableData.length }}</span
              >条数据</span
            >
            <div style="text-align: right; cursor: pointer" class="handle">
              <!-- <a
                href="javascript:;"
                style="margin: 0 10px 0 0"
                @click="addResourceHandle"
                >新增</a
              > -->
              <a
                class="addStyle"
                style="margin-right: 8px; color: #fff"
                @click="addResourceHandle"
                v-permission:yhManage="['add']"
              >
                <a-icon type="plus" />新增
              </a>
            </div>
          </div>
          <div style="margin-top: 40px">
            <a-table
              :columns="columns"
              :data-source="tableData"
              :pagination="pagination"
              size="small"
            >
              <template slot="operation" slot-scope="text, record, index">
                <div class="editable-row-operations">
                  <a
                    href="javascript:;"
                    @click="updateResourceHandle(text, record, true)"
                  >
                    查看</a
                  >
                  <a
                    href="javascript:;"
                    style="margin: 0 10px"
                    @click="updateResourceHandle(text, record, false)"
                  >
                    编辑</a
                  >

                  <a
                    v-if="record.shieldForUserTenant == 0"
                    href="javascript:;"
                    @click="enableResourceHandle(text, record, index)"
                    >禁用</a
                  >
                  <a
                    v-else
                    href="javascript:;"
                    @click="enableResourceHandle(text, record, index)"
                    >启用</a
                  >
                  <a
                    href="javascript:;"
                    style="margin: 0 10px"
                    @click="passwordResetHandle(text, record, index)"
                    >密码重置</a
                  >
                  <a
                    href="javascript:;"
                    @click="characterSetHandle(text, record, index)"
                    >角色设置</a
                  >
                </div>
              </template>
            </a-table>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <a-modal
      title="新增"
      width="40%"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="visible = false"
    >
      <a-form-model
        ref="ruleForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
        :model="menuObj"
        :rules="rules"
      >
        <a-form-model-item
          ref="parentName"
          label="部门名称"
          prop="treeDataSelect"
        >
          <a-tree-select
            v-model="treeDataSelect"
            style="width: 100%"
            :tree-data="treeData"
            tree-checkable
            :show-checked-strategy="SHOW_PARENT"
            search-placeholder="请选择部门"
            :treeCheckStrictly="true"
            :replaceFields="replaceFields"
            :treeDefaultExpandAll="true"
            allowClear
            @change="treeselectHandle()"
          />
        </a-form-model-item>
        <a-form-model-item label="姓名" prop="name">
          <a-input v-model="menuObj.name" />
        </a-form-model-item>
        <a-form-model-item label="用户账号" prop="loginName">
          <a-input v-model="menuObj.loginName"></a-input>
        </a-form-model-item>
        <a-form-model-item label="员工编号" prop="userNo">
          <a-input v-model="menuObj.userNo"></a-input>
        </a-form-model-item>
        <a-form-model-item label="岗位" prop="postIds">
          <a-select
            mode="multiple"
            showSearch
            :value="groupName"
            placeholder="请选择"
            style="width: 400px"
            :defaultActiveFirstOption="false"
            :showArrow="false"
            :filterOption="false"
            @search="handleSearch"
            @change="handleSearchChange"
            :allowClear="true"
            :notFoundContent="null"
          >
            <a-select-option v-for="d in groupDatas" :key="d.value">{{
              d.text
            }}</a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="身份证号码" prop="idCardNo">
          <a-input v-model="menuObj.idCardNo"></a-input>
        </a-form-model-item>

        <a-form-model-item label="手机号" prop="mobilePhone">
          <a-input v-model="menuObj.mobilePhone"></a-input>
        </a-form-model-item>

        <a-form-model-item label="备注" prop="remark">
          <a-input v-model="menuObj.remark"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
      :title="flag ? '查看' : '编辑'"
      width="40%"
      :visible="visibles"
      :confirm-loading="confirmLoading"
      @ok="handleEditor"
      @cancel="visibles = false"
    >
      <a-form-model
        ref="ruleFormEditor"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
        :model="menuObj"
        :rules="rules"
      >
        <a-form-model-item
          ref="parentNames"
          label="部门名称"
          prop="editDataSelect"
        >
          <a-tree-select
            :disabled="flag"
            v-model="editDataSelect"
            style="width: 100%"
            :tree-data="treeData"
            tree-checkable
            :show-checked-strategy="SHOW_PARENT"
            search-placeholder="请选择部门"
            :treeCheckStrictly="true"
            :replaceFields="replaceFields"
            :treeDefaultExpandAll="true"
            allowClear
            @change="editselectHandle()"
          />
        </a-form-model-item>
        <a-form-model-item label="姓名" prop="name">
          <a-input :disabled="flag" v-model="editorObj.name" />
        </a-form-model-item>

        <a-form-model-item label="用户账号" prop="loginName">
          <a-input :disabled="flag" v-model="editorObj.loginName"></a-input>
        </a-form-model-item>
        <a-form-model-item label="员工编号" prop="userNo">
          <a-input :disabled="flag" v-model="editorObj.userNo"></a-input>
        </a-form-model-item>
        <a-form-model-item label="岗位" prop="postIds">
          <a-select
            :disabled="flag"
            mode="multiple"
            showSearch
            :value="groupNames"
            placeholder="请选择"
            style="width: 370px"
            :defaultActiveFirstOption="false"
            :showArrow="false"
            :filterOption="false"
            @search="handleSearch"
            @change="handleSearchChanges"
            :allowClear="true"
            :notFoundContent="null"
          >
            <a-select-option v-for="d in groupDatas" :key="d.value">{{
              d.text
            }}</a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="身份证号码" prop="idCardNo">
          <a-input :disabled="flag" v-model="editorObj.idCardNo"></a-input>
        </a-form-model-item>

        <a-form-model-item label="手机号" prop="mobilePhone">
          <a-input :disabled="flag" v-model="editorObj.mobilePhone"></a-input>
        </a-form-model-item>

        <a-form-model-item label="备注" prop="remark">
          <a-input :disabled="flag" v-model="editorObj.remark"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
      title="角色设置"
      width="40%"
      :visible="visibleRole"
      :confirm-loading="confirmLoading"
      @ok="handleRoleOk"
      @cancel="visibleRole = false"
    >
      <a-transfer
        :data-source="mockData"
        :titles="['未选择角色', '已选择角色']"
        :filter-option="filterOption"
        :target-keys="targetKeys"
        :render="(item) => item.name"
        @change="handleChange"
        @search="handleShuttle"
        :disabled="false"
      />
    </a-modal>
  </div>
</template>

<script>
import { TreeSelect } from "ant-design-vue";
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

import {
  queryListForOrgsAA,
  // gwQueryListPageA,
  queryOrgTreeA,
  yhQuertPageA,
  yhSaveA,
  yhUpdateA,
  resetPassword,
  selectRoleList,
  savesRoleList,
  editEnteringData,
  disableBtn,
} from "../../services/system";
export default {
  name: "MenuManage",
  data() {
    return {
      treeDataSelect: [],
      editDataSelect: [],
      // treeDataS,
      SHOW_PARENT,

      flag: false,
      mockData: [],
      targetKeys: [],
      roleIds: "",
      visibles: false,
      searchFormData: {
        name: "",
      },

      groupName: [],
      groupDatas: [],
      groupNames: [],
      channelList: [],
      query: {
        appInfoCode: null,
        channelType: null,
      },
      searchValue: "",
      treeData: [],
      replaceFields: {
        title: "name",
        key: "code",
        value: "id",
        children: "child",
      },
      visible: false,
      confirmLoading: false,
      parentObj: {},
      visibleRole: false,
      editorObj: {
        plantUserNumber: null,
        orgNames: "",
        orgIds: null,
        orgDesc: null,
        name: null,
        postIds: "",
        code: null,
        userNo: null,
        tenantCode: sessionStorage.getItem("tenantCode"),
      },
      menuObj: {
        plantUserNumber: null,
        orgIds: null,
        orgDesc: null,
        name: null,
        postIds: "",
        code: null,
        userNo: null,

        tenantCode: sessionStorage.getItem("tenantCode"),
      },
      orgIdsA: [],
      orgIdsB: [],
      rules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }],
        userNo: [{ required: true, message: "不能为空", trigger: "blur" }],
        loginName: [{ required: true, message: "不能为空", trigger: "blur" }],

        mobilePhone: [{ required: true, message: "不能为空", trigger: "blur" }],

        postIds: [{ required: true, message: "不能为空", trigger: "blur" }],
        // treeDataSelect: [{ required: true, message: "不能为空", trigger: "blur" }],

        contactPhone: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      columns: [
        {
          title: "姓名",
          dataIndex: "name",
        },
        {
          title: "用户账号",
          dataIndex: "loginName",
        },

        {
          title: "部门名称",
          dataIndex: "orgNames",
        },

        {
          title: "岗位",
          dataIndex: "postNames",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
        },

        {
          title: "操作",
          dataIndex: "Action",
          scopedSlots: { customRender: "operation" },
        },
      ],
      tableData: [],
    };
  },
  created() {
    // const parma = {
    //   orgId: "",
    //   tenantCode: sessionStorage.getItem("tenantCode"),
    // };
    // gwQueryListPageA(parma).then((res) => {
    //   res.data.data.rows.forEach((r) => {
    //     console.log(r);
    //     this.groupDatas.push({
    //       value: r.id,
    //       text: r.name,
    //     });
    //   });
    // });
    this.getRoleList();
  },
  methods: {
    handleSearch(value) {
      console.log("handleSearch", value);
      this.debouncedGetGroup();
    },
    handleSearchChange(value) {
      this.groupName = value;
      this.menuObj.postIds = this.groupName.join(",");
      console.log("handleSearchChange", this.groupName);
    },
    handleSearchChanges(value) {
      this.groupNames = value;
      this.editorObj.postIds = this.groupNames.join(",");
      console.log("handleSearchChanges", this.groupNames);
    },
    //编辑-树结构选择
    editselectHandle() {
      this.orgIdsB = [];
      for (var i = 0; i < this.editDataSelect.length; i++) {
        this.orgIdsB.push(this.editDataSelect[i].value);
      }
      this.editorObj.orgIds = this.orgIdsB.join(",");
      this.groupDatas = [];
      this.groupNames = [];

      const parma = {
        orgIds: this.editorObj.orgIds,
        tenantCode: sessionStorage.getItem("tenantCode"),
      };
      queryListForOrgsAA(parma).then((res) => {
        res.data.data.rows.forEach((r) => {
          console.log(r);
          this.groupDatas.push({
            value: r.id,
            text: r.name,
          });
        });
      });
    },
    //树结构选择
    treeselectHandle() {
      this.orgIdsA = [];
      for (var i = 0; i < this.treeDataSelect.length; i++) {
        this.orgIdsA.push(this.treeDataSelect[i].value);
      }

      this.menuObj.orgIds = this.orgIdsA.join(",");
      this.groupDatas = [];
      this.groupName = [];
      const parma = {
        orgIds: this.menuObj.orgIds,
        tenantCode: sessionStorage.getItem("tenantCode"),
      };
      queryListForOrgsAA(parma).then((res) => {
        res.data.data.rows.forEach((r) => {
          console.log(r);
          this.groupDatas.push({
            value: r.id,
            text: r.name,
          });
        });
      });
    },
    getRoleList() {
      const parma = {
        orgId: this.parentObj.id,
        isPostNull: 0,
        tenantCode: sessionStorage.getItem("tenantCode"),
      };
      yhQuertPageA(parma).then((res) => {
        this.tableData = res.data.data.rows;
      });
      const parmas = {
        tenantCode: sessionStorage.getItem("tenantCode"),
      };
      queryOrgTreeA(parmas).then((res) => {
        this.treeData = res.data.data;
      });
    },
    selectTreeNodes(selectedKeys, e) {
      console.log(e);
      console.log(selectedKeys);
    },
    selectTreeNode(selectedKeys, e) {
      this.parentObj = e.node.dataRef;
      this.menuObj.orgId = this.parentObj.parentId;
      this.menuObj.tenantCode = sessionStorage.getItem("tenantCode");
      const parma = {
        orgId: this.parentObj.id,
        tenantCode: sessionStorage.getItem("tenantCode"),
        isPostNull: 0,
      };
      yhQuertPageA(parma).then((res) => {
        this.tableData = res.data.data.rows;
      });
    },

    //新增按钮
    handleOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          let handle;
          console.log("1===", this.menuObj);
          if (this.menuObj.id) {
            handle = yhUpdateA(this.menuObj.id, this.menuObj);
          } else {
            console.log(this.menuObj);
            handle = yhSaveA(this.menuObj);
          }
          handle
            .then((res) => {
              this.confirmLoading = false;
              if (res.data.status == 0) {
                this.visible = false;
                this.getRoleList();
              }
            })
            .catch((error) => {
              console.log(error);
              this.confirmLoading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //新增
    addResourceHandle() {
      this.dataType = 1;
      this.treeDataSelect = [];
      this.menuObj = {
        name: null,
        orgIds: null,
        type: null,
        orgDesc: null,
        code: null,
        tenantCode: sessionStorage.getItem("tenantCode"),
      };
      (this.groupName = []), (this.visible = true);
    },
    //编辑
    updateResourceHandle(text, item, flag) {
      this.flag = flag;
      this.editrId = item.id;
      (this.editorObj = {
        orgNames: item.orgNames || "",
        name: item.name || "",
        orgIds: item.orgInfos.map((datas) => datas.id).join(","),
        postIds: item.postInfos.map((items) => items.id).join(","),
        loginName: item.loginName || "",
        userNo: item.userNo || "",
        idCardNo: item.idCardNo || "",
        email: item.email || "",
        mobilePhone: item.mobilePhone || "",
        remark: item.remark || "",
        tenantCode: sessionStorage.getItem("tenantCode"),
      }),
        // (this.groupNames = item.postInfos.map((items) => items.id));

        (this.groupNames = item.postInfos.map((items) => items.name));

      console.log();
      this.editDataSelect = item.orgInfos.map((res) => {
        return {
          title: res.name,
          key: res.code,
          value: res.id,
          children: res.children,
        };
      });
      this.dataType = 1;
      this.visibles = true;
    },
    //编辑按钮
    handleEditor() {
      if (!this.flag) {
        editEnteringData(this.editrId, this.editorObj).then((res) => {
          if (res.data.status == 0) {
            this.visibles = false;
            this.getRoleList();
          }
        });
      } else {
        this.visibles = false;
      }
    },
    //禁用、启用
    enableResourceHandle(text, item) {
      let vm = this;

      if (item.shieldForUserTenant == 0) {
        //要去禁用
        vm.title = "您确定要禁用该数据？";
      } else {
        //要去启用
        vm.title = "您确定要启用该数据？";
      }
      this.$confirm({
        title: vm.title,
        onOk() {
          if (item.shieldForUserTenant == 0) {
            //要去禁用
            item.shieldForUserTenant = 1;
          } else {
            //要去启用
            item.shieldForUserTenant = 0;
          }

          return new Promise((resolve, reject) => {
            disableBtn(
              item.id,
              sessionStorage.getItem("tenantCode"),
              sessionStorage.getItem("subjectInfoId"),
              item.shieldForUserTenant
            ).then((res) => {
              if (res.data.status == 0) {
                vm.getRoleList();
                resolve();
              } else {
                reject(res.data.msg);
              }
            });
          });
        },
        onCancel() {},
      });
    },
    //密码重置
    passwordResetHandle(text, item) {
      let vm = this;
      this.$confirm({
        title: "您确定要重置密码？",
        onOk() {
          return new Promise((resolve, reject) => {
            resetPassword(item.id).then((res) => {
              if (res.data.status == 0) {
                vm.$message.success(res.data.msg);
                vm.getRoleList();
                resolve();
              } else {
                reject(res.data.msg);
              }
            });
          });
        },
        onCancel() {},
      });
    },
    //角色设置
    characterSetHandle(text, item) {
      this.visibleRole = true;
      this.getMock(item.id);
      this.handleRoleOkId = item.id;
    },
    //角色设置确定按钮
    handleRoleOk() {
      let params = {
        id: this.handleRoleOkId,
        roleIds: this.roleIds,
        tenantCode: sessionStorage.getItem("tenantCode"),
      };
      this.confirmLoading = true;
      savesRoleList(params)
        .then(({ data }) => {
          this.$message.success(data.msg);
          this.confirmLoading = false;
          if (data.status == 0) {
            this.visibleRole = false;
          }
        })
        .catch((error) => {
          console.log(error);
          this.confirmLoading = false;
        });
    },
    //穿梭框填数据
    getMock(id) {
      const targetKeys = [];
      let tenantCode = sessionStorage.getItem("tenantCode");
      selectRoleList(id, tenantCode).then((res) => {
        let selectRoleList = res.data.data.selectRoleList;
        res.data.data.allRoleList.forEach((item, index) => {
          item["key"] = index.toString();
          selectRoleList.forEach((items) => {
            if (item.id == items.id) {
              targetKeys.push(item.key);
            }
          });
        });
        this.targetKeys = targetKeys;
        this.roleIds = selectRoleList.map((item) => item.id).join(",");
        this.mockData = res.data.data.allRoleList;
      });
    },
    filterOption(inputValue, option) {
      return option.description.indexOf(inputValue) > -1;
    },
    handleChange(targetKeys, direction, moveKeys) {
      console.log(targetKeys, direction, moveKeys, 222);
      this.targetKeys = targetKeys;
      const roleIdsList = [];
      this.mockData.forEach((item) => {
        targetKeys.forEach((items) => {
          if (item.key == items) {
            roleIdsList.push(item);
          }
        });
      });
      this.roleIds = roleIdsList.map((item) => item.id).join(",");
    },
    handleShuttle(dir, value) {
      console.log("search:", dir, value, 333);
    },
    //搜索
    searchBtnClick() {
      const parma = {
        orgId: this.menuObj.orgId,
        name: this.searchFormData.name,
        tenantCode: sessionStorage.getItem("tenantCode"),
        isPostNull: 0,
      };
      yhQuertPageA(parma).then((res) => {
        this.tableData = res.data.data.rows;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.conditionsSearch {
  border: 1px solid #eee;
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 4px 4px 0 0;
  margin-top: 15px;
}
.search-wrapper {
  border-radius: 0 0 4px 4px;
  display: flex;
  background-color: #fff;
  align-items: center;
  border: 1px solid #eee;
  border-top: none;
  padding-left: 12px;
  padding-bottom: 8px;
}
.topAntform {
  width: 285px;
  height: 48px;
}
.serach-input {
  display: flex;
  padding-top: 5px;
  input {
    margin-left: 10px;
    height: 30px;
  }
}
.btn-group {
  padding: 0;
  button {
    background-color: #fff !important;
    color: #666 !important;
  }
}
/deep/ .ant-card {
  padding-top: 0;
}
.addStyle {
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgb(0, 121, 254);
  width: 78px;
  height: 30px;
}
.menu {
  .handle {
    i {
      margin: 0 10px;
      font-size: 16px;
      cursor: pointer;
    }
  }
}
</style>
